define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'mox/play/info/index' + location.search,
                    add_url: 'mox/play/info/add',
                    edit_url: 'mox/play/info/edit',
                    del_url: 'mox/play/info/del',
                    multi_url: 'mox/play/info/multi',
                    import_url: 'mox/play/info/import',
                    table: 'mox_play_info',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id') },
                        { field: 'type.title', title: __('类型') },
                        { field: 'title', title: __('Title'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        { field: 'image', title: __('Image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image },
                        {
                            field: 'video',
                            title: __('Video'),
                            operate: false,
                            formatter: function (value, row, index) {
                                if (!value) return '';

                                // 安全检查：防止XSS
                                value = Controller.api.safeVideoUrl(value);

                                // 视频格式识别
                                const ext = value.split('.').pop().toLowerCase();
                                const isVideo = ['mp4', 'webm', 'ogg'].includes(ext);

                                // 显示逻辑
                                if (isVideo) {
                                    return ` 
                                    <div class="video-cell">
                                    <i class="fa fa-film text-primary"></i>
                                    <a href="javascript:;" 
                                    class="video-preview" 
                                    data-url="${value}"
                                    data-title="${row.title || '视频预览'}">
                                    ${row.videofilename.filename}
                                    </a>
                                    ${row.video_thumb ? `<img src="${row.video_thumb}" class="video-thumb">` : ''}
                                    </div>
                                    `;
                                }
                                return `<a href="${value}" target="_blank">${row.videofilename.filename}</a>`;
                            },
                            events: {
                                'click .video-preview': function (e, value, row, index) {
                                    Controller.api.showVideoModal(value, row.title);
                                }
                            }
                        },
                        { field: 'story.title', title: __('故事') },
                        { field: 'chapter.title', title: __('章节') },
                        {
                            field: 'related_persons',
                            title: __('Related_persons'),
                            operate: 'LIKE',
                            table: table,
                            class: 'autocontent',
                            formatter: function (value, row, index) {
                                if (!value || value == '') {
                                    return '无';
                                }
                                return row.relatedpersons.map((person, i) => {
                                    const imgContainerStyle = `
                                    display: inline-block;
                                    width: 20px;
                                    height: 20px;
                                    border-radius: 10px;
                                    overflow: hidden;
                                    margin-right: 5px;
                                    margin-bottom: 5px;
                                    vertical-align: middle;
                                    `;
                                    const imgStyle = ` width: 100%;height: 100%;object-fit: cover; display: block;`;
                                    const tooltipContent = `<div style="max-width: 300px; max-height: 300px; padding: 10px;">
                                    <div style="display: flex; align-items: start; gap: 10px; ">
                                    ${person.image ? ` <div style="min-width: 60px; height: 60px; border-radius: 10px; overflow: hidden;">
                                        <img src="${person.image}" style="width: 100%; height: 100%; object-fit: cover; border-radius: 10px;">
                                    </div> ` : ''}
                                    <div style="width: 80%;">
                                    <strong>${person.name || '未知'}</strong>
                                    ${person.era ? `<div style="color:#ffffff; font-size:0.9em;">${person.era}</div>` : ''}
                                    ${person.brief_introduction ? `<div style="color:#ffffff; font-size:0.9em; ">${person.brief_introduction}</div>` : ''}
                                    </div></div></div>`;
                                    const uniqueId = `tooltip-${index}-${i}`;
                                    // 绑定 mouseenter 事件，在页面渲染后生效
                                    setTimeout(() => {
                                        $(`#${uniqueId}`).off('mouseenter').on('mouseenter', function () {
                                            layer.tips(tooltipContent, this, {
                                                tips: [1, '#333'],
                                                time: 0,
                                                area: ['auto', 'auto'],
                                                shade: 0,
                                                shadeClose: true,
                                                skin: 'layui-layer-lan'
                                            });
                                        }).off('mouseleave').on('mouseleave', function () {
                                            layer.closeAll('tips');
                                        });
                                    }, 10);
                                    return `<div style="margin: 3px 0; line-height: 1.5;">
                                    ${person.image ? `<span style="${imgContainerStyle}">
                                        <img src="${person.image}" style="${imgStyle}" onerror="this.style.display='none'">
                                        </span>` : ''}
                                        <span id="${uniqueId}" style="cursor: pointer; vertical-align: middle; color: #007bff;">
                                        ${person.name || '未知'}</span></div>`;
                                }).join('');
                            }
                        },
                        { field: 'brief_introduction', title: __('Brief_introduction'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        {
                            field: 'msg_num', title: __('评论管理'), operate: false,
                            formatter: function (value, row, index) {
                                let num = value > 0 ? `<b style="color: #26ffb6;">（${value}）</b>` : '';
                                return `<a href="mox/play/msg/index?p_id=${row.id}" class="btn btn-xs btn-info btn-dialog" data-area="[&quot;95%&quot;,&quot;95%&quot;]" data-shade="[0.5,&quot;#000&quot;]" title="评论管理"><i class="fa fa-list"></i> 评论管理${num}</a>`;
                            }
                        },
                        { field: 'num', title: __('浏览次数') },
                        {
                            field: 'is_perform',
                            title: __('是否演出'),
                            align: 'center',
                            formatter: Table.api.formatter.toggle,
                            operate: false
                        },
                        {
                            field: 'is_represent',
                            title: __('是否代表作'),
                            align: 'center',
                            table: table,
                            formatter: Table.api.formatter.toggle
                        },
                        { field: 'user.nickname', title: __('关联用户') },
                        { field: 'create_time', title: __('Create_time'), sortable: true, formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange' },
                        { field: 'update_time', title: __('Update_time'), sortable: true, formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange' },
                        { field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
            $(function () {
                function toggleCidVisible() {
                    var s_id = $('#c-s_id').val();
                    if (s_id && parseInt(s_id) !== 0) {
                        $('#c-c_id').closest('.form-group').show();
                    } else {
                        $('#c-c_id').closest('.form-group').hide();
                    }
                }

                // 初始时判断一次
                toggleCidVisible();

                // 当 s_id 改变时重新判断
                $(document).on("change", "#c-s_id", function () {
                    toggleCidVisible();
                });
            });
        },
        edit: function () {
            Controller.api.bindevent();


            $(function () {
                function toggleCidVisible() {
                    var s_id = $('#c-s_id').val();
                    if (s_id && parseInt(s_id) !== 0) {
                        $('#c-c_id').closest('.form-group').show();
                    } else {
                        $('#c-c_id').closest('.form-group').hide();
                    }
                }

                // 初始时判断一次
                toggleCidVisible();

                // 当 s_id 改变时重新判断
                $(document).on("change", "#c-s_id", function () {
                    toggleCidVisible();
                });
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            // 安全处理视频URL
            safeVideoUrl: function (url) {
                if (!url) return '';
                // 移除可能的恶意脚本
                return url.replace(/[\"\'<>]/g, '');
            },

            // 显示视频模态框
            showVideoModal: function (url, title) {
                const safeUrl = this.safeVideoUrl(url);
                const ext = safeUrl.split('.').pop().toLowerCase();
                const mimeTypes = {
                    mp4: 'video/mp4',
                    webm: 'video/webm',
                    ogg: 'video/ogg'
                };

                const modal = `
        <div class="modal fade" id="videoModal" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">${title || '视频预览'}</h5>
                        <button type="button" class="close" data-dismiss="modal">
                            <span>&times;</span>
                        </button>
                    </div>
                    <div class="modal-body text-center">
                        <video controls class="embed-responsive-item" style="width:100%">
                            <source src="${safeUrl}" type="${mimeTypes[ext] || 'video/mp4'}">
                            您的浏览器不支持HTML5视频
                        </video>
                    </div>
                    <div class="modal-footer">
                        <a href="${safeUrl}" class="btn btn-default" download>
                            <i class="fa fa-download"></i> 下载视频
                        </a>
                    </div>
                </div>
            </div>
        </div>`;

                $(modal).appendTo('body').modal('show')
                    .on('hidden.bs.modal', function () {
                        $(this).remove();
                    });
            }
        }
    };
    return Controller;
});
